package com.lln.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lln.mapper.DeviceBrandMapper;
import com.lln.pojo.DeviceBrand;
import com.lln.service.DeviceBrandService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DeviceBrandServiceImpl extends ServiceImpl<DeviceBrandMapper, DeviceBrand> implements DeviceBrandService {
    @Override
    public boolean uploadDeviceBrand(MultipartFile file) throws Exception {
        if(file == null || file.isEmpty()){
            throw new Exception("上传的文件不能为空");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!".xls,.xlsx".toUpperCase().contains(suffix.toUpperCase())) {
            throw new Exception("请使用.xls,.xlsx");
        }
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        List<DeviceBrand> deviceBrands = new ArrayList<>();
        Sheet sheet = workbook.getSheetAt(0);
        for(int i = 1; i <= sheet.getLastRowNum(); i++){
            Row row = sheet.getRow(i);
            Cell cell1 = row.getCell(0);
            String name = cell1.getStringCellValue();
            Cell cell2 = row.getCell(1);
            String brandCode = cell2.getStringCellValue();
            Cell cell3 = row.getCell(2);
            String remark = cell3.getStringCellValue();
            Cell cell4 = row.getCell(3);
            Integer deviceTypeId = (int) cell4.getNumericCellValue();
            Cell cell5 = row.getCell(4);
            Integer createId = (int) cell5.getNumericCellValue();
            Cell cell6 = row.getCell(5);
            Date createTime = cell6.getDateCellValue();

            DeviceBrand deviceBrand = new DeviceBrand();
            deviceBrand.setName(name);
            deviceBrand.setBrandCode(brandCode);
            deviceBrand.setRemark(remark);
            deviceBrand.setDeviceTypeId(deviceTypeId);
            deviceBrand.setCreateId(createId);
            Timestamp timestamp = new Timestamp(createTime.getTime());
            deviceBrand.setCreateTime(timestamp);
            deviceBrands.add(deviceBrand);
        }
        return this.saveBatch(deviceBrands);
    }
}
